#include "Manage.h"
#include "ui_Manage.h"
#include "Server.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Manage::Manage(Server *server, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Manage)
    , serverWindow(server)
    , employeeModel(new QStringListModel(this))
    , groupModel(new QStringListModel(this))
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("attendance_system.db");

    if (!db.open()) {
        // QMessageBox::critical(this, "错误", "无法打开数据库: " + db.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法打开数据库: " + db.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    refreshPageData();
}

Manage::~Manage()
{
    delete ui;
}

// 实现窗口拖动功能
void Manage::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Manage::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Manage::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Manage::refreshPageData() {
    loadEmployeeInfo();
    loadGroupInfo();
}

void Manage::loadEmployeeInfo() {
    QSqlQuery query;
    query.exec("SELECT 工号, 姓名, 密码, 标签号 FROM EmployeeInfo");

    QStringList employeeList;
    while (query.next()) {
        QString empNum = query.value(0).toString();
        QString empName = query.value(1).toString();
        QString password = query.value(2).toString();
        int tag = query.value(3).toInt();

        QString displayText = empNum + "-" + empName;
        if (password.isEmpty()) {
            displayText += "-未认证";
        } else if (tag == 0) {
            displayText += "-未录入";
        } else {
            displayText += "-已录入";
        }

        employeeList << displayText;
    }

    employeeModel->setStringList(employeeList);
    ui->man->setModel(employeeModel);
}

void Manage::loadGroupInfo() {
    QSqlQuery query;
    query.exec("SELECT 考勤组号 FROM AttendanceGroup");

    QStringList groupList;
    while (query.next()) {
        QString groupNumber = query.value(0).toString();
        groupList << groupNumber;
    }

    groupModel->setStringList(groupList);
    ui->group->setModel(groupModel);
}

void Manage::on_returnButton_clicked()
{
    this->close();
    serverWindow->show();
    serverWindow->checkAttendanceGroups();
}


void Manage::on_set_clicked()
{
    Team *team = new Team(this);
    team->show();
    this->hide();
}


void Manage::on_add_clicked()
{
    Add *add = new Add(this);
    add->show();
    this->hide();
}

void Manage::on_man_clicked(const QModelIndex &index) {
    QString itemText = index.data().toString();
    QStringList parts = itemText.split("-");
    QString employeeId = parts[0];
    QString employeeName = parts[1];

    QString personalTable = QString("`%1_%2`").arg(employeeId).arg(employeeName);
    QSqlQuery query;
    query.prepare(QString("SELECT 考勤组号 FROM %1").arg(personalTable));

    QStringList groupNumbers;  // 用于存储多个考勤组号
    if (query.exec()) {
        while (query.next()) {
            QString groupNumber = query.value(0).toString();
            groupNumbers << groupNumber;
        }

        if (!groupNumbers.isEmpty()) {
            // 将考勤组号添加到QListView的模型中
            QStringListModel *model = new QStringListModel(this);
            model->setStringList(groupNumbers);
            ui->group1->setModel(model);
        } else {
            // QMessageBox::warning(this, "警告", "没有找到考勤组号");
            MyMessageBox msgBox;
            msgBox.setWindowTitle("警告");
            msgBox.setText("没有找到考勤组号");
            msgBox.setButton("确定");
            msgBox.exec();
        }
    } else {
        // QMessageBox::warning(this, "警告", "无法获取考勤组号");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("无法获取考勤组号");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Manage::on_group_clicked(const QModelIndex &index) {
    QString groupNumber = index.data().toString();

    QSqlQuery query;
    QString groupTable = QString("`%1`").arg(groupNumber);

    // 查询员工工号和姓名
    query.prepare(QString("SELECT 工号, 姓名 FROM %1").arg(groupTable));
    QStringList employeeList;
    if (query.exec()) {
        while (query.next()) {
            QString empNum = query.value(0).toString();
            QString empName = query.value(1).toString();
            employeeList << empNum + "-" + empName;
        }

        // 将结果设置到man1的QListView中
        QStringListModel *model = new QStringListModel(this);
        model->setStringList(employeeList);
        ui->man1->setModel(model);
    } else {
        // QMessageBox::warning(this, "警告", "无法加载员工信息");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("无法加载员工信息");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 查询开始时间、结束时间、考勤日期
    query.prepare("SELECT 开始时间, 结束时间, 考勤日期 FROM AttendanceGroup WHERE 考勤组号 = :groupNumber");
    query.bindValue(":groupNumber", groupNumber);
    if (query.exec() && query.next()) {
        // 设置开始时间和结束时间到QLineEdit
        ui->start->setText(query.value(0).toTime().toString("HH:mm:ss"));
        ui->end->setText(query.value(1).toTime().toString("HH:mm:ss"));

        // 解析考勤日期，并设置到QListView
        QString attendanceDates = query.value(2).toString();
        QStringList dateList;
        QStringList daysOfWeek = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        for (int i = 0; i < attendanceDates.size(); ++i) {
            if (attendanceDates[i] == '1') {
                dateList << daysOfWeek[i];  // 如果为'1'，则添加对应的星期几
            }
        }

        // 设置解析后的日期到QListView的模型
        QStringListModel *dateModel = new QStringListModel(this);
        dateModel->setStringList(dateList);
        ui->date->setModel(dateModel);

    } else {
        // QMessageBox::warning(this, "警告", "无法加载考勤组信息");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("无法加载考勤组信息");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}
